<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>蛇</title>
    <style>
        table{
            border: 1px solid red;
            margin: 0px auto;
        }
        td{
            border: 1px solid green;
            width: 20px;
            height: 20px;
        }
    </style>
</head>
<body>
    <script>
        const columnNum = 10;//常量  不可改变

        var selectedIndex = 4

        var table = document.createElement('table')
         document.body.appendChild(table)
        var tr = table.insertRow()
        var tds = [];
       for(var i=0;i<columnNum;i++){
           var td = tr.insertCell()
           tds.push(td)
           if(i==selectedIndex){
            td.style.backgroundColor = 'black'
           }
       }
       document.body.onkeydown = function(e){
           if(e.keyCode == 37){//左
               if(selectedIndex==0){
                return
               }
               tds[selectedIndex].style.backgroundColor = 'white'
               selectedIndex--;
               tds[selectedIndex].style.backgroundColor = 'black'
               
           }
           else if(e.keyCode == 39){//右
               if(selectedIndex==columnNum-1){
                return
               }
               tds[selectedIndex].style.backgroundColor = 'white'
               selectedIndex++;
               tds[selectedIndex].style.backgroundColor = 'black'
           }
       }
    //    document.body.addEventListener("click",function(e){

    //    },true)
    </script>
</body>
</html>